<?php defined('BASEPATH') OR die('No direct access allowed.');
/**
 * Description of Main
 *
 * Created on Dec 09, 2010
 * @author Ramon Gutierrez
 * @copyright Bitstop Network Services Inc.
 * @version 0.1
 */
class Main extends Controller {
	function Main() {
		parent::Controller();
		global $header, $data;
		
		// Header variables
		$header['extras'] = "";
		$header['grid'] = false;
		$data['module'] = 'main';
	}
	
	function index() {
		global $header, $data;
		
		// Load up that header!
		$header['title'] = $this->lang->line('title_main');
							
		$this->load->view('header', $header);
		
		// Load the sidebar
		$this->load->view('sidebar-left', $data);

		// Dish out the meat
		$this->load->view($this->session->userdata('account_id') ? 'main-user' : 'main-guest', $data);
		
		// Let's see that footer!
		$this->load->view('footer');
	}
	
	function settings() {
		global $header, $data;
		
		// Check if user is logged in
		if(!$this->session->userdata('account_id') ||
		($this->session->userdata('account_type') != 'site_admin' && $this->session->userdata('account_type') != 'company')) {
			redirect(site_url(), 'refresh');
		}
		
		// Load model
		$this->load->model('settings_model');
		
		// Load up that header!
		$header['title'] = $this->lang->line('title_settings');
		$header['extras'] = '<script type="text/javascript">' . "\n" .
							'// <![CDATA[' . "\n" .
							'  $(document).ready(function() {' . "\n" .
							'    var options = {' . "\n" .
							'        target:         "#response",' . "\n" .
							'        success:        showResponse' . "\n" .
							'    };' . "\n\n" .
							'    $("#theform").ajaxForm(options);' . "\n" .
							'    function showResponse(responseText, statusText) {' . "\n" .
							'      $("#response").html(responseText).show();' . "\n" .
							'      if(responseText == "Settings have been saved") {' . "\n" .
							'        $("#response").css("border", "1px solid #c8fb6e");' . "\n" .
							'        $("#response").css("backgroundColor", "#eaffb9");' . "\n" .
							'        window.scrollTo(0,0);' . "\n" .
							'        alert(responseText);' . "\n" .
							'        window.location = "' . site_url($data['module']) . '/";' . "\n" .
							'        //alert(responseText);' . "\n" .
							'      } else {' . "\n" .
							'        $("#response").css("border", "1px solid #fa4646");' . "\n" .
							'        $("#response").css("backgroundColor", "#fabfbf");' . "\n" .
							'        submitted = false;' . "\n" .
							'        window.scrollTo(0,0);' . "\n" .
							'      }' . "\n" .
							'    };' . "\n" .
							'  });' . "\n" .
							'// ]]>' . "\n" .
							'</script>' . "\n\n";
							
		$this->load->view('header', $header);
		
		// Load the sidebar
		$this->load->view('sidebar-left', $data);
		
		// Additional data
		$data['settings'] = $this->settings_model->getConfig($this->session->userdata('client_id'));
		$data['industry_types'] = $this->common_model->getIndustryTypes();
		$data['countries'] = $this->common_model->getCountries();
		
		if($this->session->userdata('account_type') == 'company') {
			// Additional model
			$this->load->model('clients_model');
			
			// Get client info
			$data['info'] = $this->clients_model->getClientInfo($this->session->userdata('client_id'));
		}

		// Dish out the meat
		$this->load->view('main-settings', $data);
		
		// Let's see that footer!
		$this->load->view('footer');
	}
	
	function settings_ajax() {
		global $header, $data;
		
		// Get info
		$info = $this->common_model->getInfo('accounts', $this->session->userdata('account_id'));
		
		// Post variables
		$post['company_name'] = $this->input->post("company_name");
		$post['industry_type'] = $this->input->post("industry_type");
		$post['first_name'] = $this->input->post("first_name");
		$post['last_name'] = $this->input->post("last_name");
		$post['street_address'] = $this->input->post("street_address");
		$post['city'] = $this->input->post("city");
		$post['state'] = $this->input->post("state");
		$post['country_id'] = $this->input->post("country_id");
		$post['zip'] = $this->input->post("zip");
		$post['email'] = $this->input->post("email");
		$post['contact_number'] = $this->input->post("contact_number");
		$post['username'] = $this->input->post("acct_username");
		$post['password'] = $this->input->post("acct_password");
		$post['confirm'] = $this->input->post("acct_confirm");
		$error = false;
		
		// Check for duplicates
		$dupe_username = $this->db->select('id')->from('accounts')->where("username = '" . $post['username'] . "' AND id != " . $this->session->userdata('account_id'))->get();
		$dupe_email = $this->db->select('id')->from('accounts')->where("email = '" . $post['email'] . "' AND id != " . $this->session->userdata('account_id'))->get();
		
		// Check for errors
		$error .= !$post['company_name'] ? "<li>Provide a company name.</li>" : '';
		$error .= !$post['industry_type'] || !is_numeric($post['industry_type']) ? "<li>Select an industry type.</li>" : '';
		$error .= !$post['first_name'] ? "<li>Enter first name of contact person.</li>" : '';
		$error .= !$post['last_name'] ? "<li>Enter last name of contact person.</li>" : '';
		$error .= !$post['street_address'] ? "<li>Provide a street address.</li>" : '';
		$error .= !$post['city'] ? "<li>Provide a city name.</li>" : '';
		$error .= !$post['state'] ? "<li>Provide a state or province.</li>" : '';
		$error .= !$post['country_id'] || !is_numeric($post['country_id']) ? "<li>Select a country.</li>" : '';
		$error .= !$post['email'] || !validate_email($post['email']) ? "<li>Provide a valid e-mail address.</li>" : ($dupe_email->num_rows() > 0 ? "<li>E-mail address is already in use.</li>" : '');
		$error .= !$post['contact_number'] ? "<li>Enter a contact number for this company.</li>" : '';
		$error .= !$post['username'] || strlen($post['username']) < 5 ? "<li>Username must have at least 5 characters.</li>" : ($dupe_username->num_rows() > 0 ? "<li>Username is already taken.</li>" : '');
		$error .= $post['password'] && strlen($post['password']) < 7 ? "<li>Password must have at least 7 characters.</li>" : '';
		$error .= $post['confirm'] != $post['password'] ? "<li>Password and confirmation fields must match.</li>" : '';
		
		if(!$error) {
			// Use old password if none provided
			$password = $post['password'] ? md5($post['password']) : $info['password'];
			
			$data = array(
						  'last_name' => $post['last_name'],
						  'first_name' => $post['first_name'],
						  'street_address' => $post['street_address'],
						  'city' => $post['city'],
						  'state' => $post['state'],
						  'country_id' => $post['country_id'],
						  'zip' => $post['zip'],
						  'email' => $post['email'],
						  'contact_number' => $post['contact_number'],
						  'username' => $post['username'],
						  'password' => md5($post['password']),
						  'account_type' => 'company'
						 );
						 
			$query1 = $this->common_model->update('accounts', $this->session->userdata('account_id'), $data);
			$query2 = false;
			
			if($query1) {
				$data = array(
							  'name' => $post['company_name'],
							  'industry_type' => $post['industry_type']
							 );
				
				$query2 = $this->common_model->update('clients', $this->session->userdata('client_id'), $data);
			}
			
			if(!$query1 || !$query2) {
				$error .= "<li>Whoops! Something seems to have gone wrong. Please try again later.</li>";
			}
		}
		
		if($error) {
			echo "<b>Please correct the following errors:</b><br /><ul class='errors'>$error</ul>";
		} else {
			echo "Settings have been saved";
		}
	}
	
	function uploadLogo() {
		if($this->session->userdata('account_type') == 'company') {
			global $header, $data;
		
			// Load up that header!
			$header['title'] = $this->lang->line('title_upload_logo');
			$header['extras'] = '<script type="text/javascript" src="' . site_url('js/ajaxupload.js') . '"></script>' . "\n" .
								'<script type="text/javascript">' . "\n" .
								'// <![CDATA[' . "\n" .
								'  $(document).ready(function() {' . "\n" .
								'    new AjaxUpload("#upload-image", { action: "' . site_url('main/doUploadLogo') . '",' . "\n" .
								'									   autoSubmit: true,' . "\n" .
								'                                      onSubmit: function(file, ext) {' . "\n" .
								'                                                  if (! (ext && /^(jpg|png|jpeg|gif)$/.test(ext))) {' . "\n" .
								'                                                    alert("Please upload a valid JPG, GIF, or PNG image.");' . "\n" .
								'                                                    return false;' . "\n" .
								'                                                  }' . "\n" .
								'                                                },' . "\n" .
								'                                      onComplete: function(file, response) {' . "\n" .
								'                                                    if(response.toLowerCase().indexOf("<" + "img") == -1) {' . "\n" .
								'                                                      alert(response);' . "\n" .
								'                                                    } else {' . "\n" .
								'                                                      var data = response.split("::");' . "\n" .
								'                                                      $("#photobox").html(data[0]);' . "\n" .
								'                                                      $("#logo-type").val(data[1]);' . "\n" .
								'                                                    }' . "\n" .
								'                                                  }' . "\n" .
								'                                    });' . "\n\n" .
								'    var options = {' . "\n" .
								'        target:         "#response",' . "\n" .
								'        success:        showResponse' . "\n" .
								'    };' . "\n\n" .
								'    $("#theform").ajaxForm(options);' . "\n" .
								'    function showResponse(responseText, statusText) {' . "\n" .
								'      $("#response").html(responseText).show();' . "\n" .
								'      if(responseText == "Logo has been changed") {' . "\n" .
								'        $("#response").css("border", "1px solid #c8fb6e");' . "\n" .
								'        $("#response").css("backgroundColor", "#eaffb9");' . "\n" .
								'        window.scrollTo(0,0);' . "\n" .
								'        refreshPhoto();' . "\n" .
								'        alert(responseText);' . "\n" .
								'        window.location = "' . site_url($data['module']) . '/";' . "\n" .
								'        //alert(responseText);' . "\n" .
								'      } else {' . "\n" .
								'        $("#response").css("border", "1px solid #fa4646");' . "\n" .
								'        $("#response").css("backgroundColor", "#fabfbf");' . "\n" .
								'        submitted = false;' . "\n" .
								'        window.scrollTo(0,0);' . "\n" .
								'      }' . "\n" .
								'    };' . "\n" .
								'  });' . "\n" .
								'// ]]>' . "\n" .
								'</script>' . "\n\n";
								
			$this->load->view('header', $header);
			
			// Load the sidebar
			$this->load->view('sidebar-left', $data);
			
			// Additional data
			$data['photo'] = (@file_exists('usr/' . $this->session->userdata('client_id') . '/logo.' . $this->session->userdata('logo')) ? site_url('usr/' . $this->session->userdata('client_id') . '/logo.' . $this->session->userdata('logo')) : site_url('images/no-image-full.png'));
	
			// Dish out the meat
			$this->load->view('main-uploadlogo', $data);
			
			// Let's see that footer!
			$this->load->view('footer');
		} else {
			// Not authorized to upload a logo
			redirect(site_url(), 'refresh');
		}
	}
	
	function logo_ajax() {
		$error = "";
		$logo_type = $this->input->post('logo-type');
		
		if(!file_exists('usr/' . $this->session->userdata('client_id') . '/temp.' . $logo_type)) {
			$error .= "<li>Nothing new was captured.</li>";
		}
		
		if(!$error) {
			// Get and purge old logo
			$old_type = $this->session->userdata('logo');
			@unlink('usr/' . $this->session->userdata('client_id') . '/logo.' . $old_type);
			
			// Replace with new logo
			$fileop = @rename('usr/' . $this->session->userdata('client_id') . '/temp.' . $logo_type, 'usr/' . $this->session->userdata('client_id') . '/logo.' . $logo_type);
			$query = $this->common_model->update('clients', $this->session->userdata('client_id'), array('logo' => $logo_type));
			$this->session->set_userdata(array('logo' => $logo_type));
			
			if(!$fileop || !$query) {
				$error .= "<li>Error while storing new logo</li>";
			}
		}
		
		if($error) {
			echo "<b>Please correct the following errors:</b><br /><ul class='errors'>$error</ul>";
		} else {
			echo "Logo has been changed";
		}
	}
	
	function doUploadLogo() {
		$image = $_FILES['userfile'];
		$id = $this->session->userdata('client_id');
		
		// Error var
		$errors = array();
		
		// Get attributes
		list($width, $height, $type, $attr) = @getimagesize($image['tmp_name']);
		$ext = strrchr($image['name'], '.');
		
		// Error checking
		if($ext != '.jpeg' && $ext != '.gif' && $ext != '.jpg' && $ext != '.png') {
			$errors[] = "Please upload a valid JPG, GIF, or PNG image.";
		}
		
		if($width > $this->config->item('max_width') || $height > $this->config->item('max_height')) {
			$errors[] = "Images must be equal to or less than " . $this->config->item('max_width') . "px wide, and " . $this->config->item('max_height') . "px high.";
		}
		
		if($image['size'] > $this->config->item('max_filesize') - 100000) {
			$max_size = ($this->config->item('max_filesize') / 1048576 > 1 ? $this->config->item('max_filesize') / 1048576 . " MB" : $this->config->item('max_filesize') / 1024 . " KB");
			$errors[] = "Upload an image with a maximum file size of " . $max_size;
		}
		
		// All clear! Do upload
		if(empty($errors)) {
			str_replace('.', '', $image['name']);
			str_replace('/', '', $image['name']);
			
			// Get next insert ID if not specified
			if(!$id) {
				$id = $this->companies_model->getNext();
			}
			
			// Create directory if doesn't exist
			@mkdir('usr/' . $id . '/');
			
			if(@move_uploaded_file($image['tmp_name'], 'usr/' . $id . '/temp' . $ext)) {
				echo '<img src="' . site_url('usr/' . $id . '/temp' . $ext) . '" alt="' . $this->lang->line('logo_new') . '" title="' . $this->lang->line('logo_new') . '" style="display: block; margin-left: auto; margin-right: auto;" />::' . str_replace('.', '', $ext);
			} else {
				echo "An error has occurred while uploading this image.";
			}
		} else { // or display the errors
			echo "Please correct the following errors:\n\n";
			foreach($errors as $error) {
				echo "- " . $error . "\n";
			}
		}
	}
	
	function getClient() {
		if($this->session->userdata('account_id')) {
			$path = $this->session->userdata('client_path');
			$mm_type = "application/octet-stream";
			
			// Create headers
			header("Pragma: public");
			header("Expires: 0");
			header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
			header("Cache-Control: public");
			header("Content-Description: File Transfer");
			header("Content-Type: " . $mm_type);
			header("Content-Length: " .(string)(filesize($path)) );
			header('Content-Disposition: attachment; filename="'.basename($path).'"');
			header("Content-Transfer-Encoding: binary\n");
			
			// Output the file
			readfile($path);
		} else {
			// Not authorized to download
			redirect(site_url(), 'refresh');
		}
	}
}

/* End of file main.php */
/* Location: ./system/application/controllers/main.php */